package com.alpaak.common.utils;

import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class RequestUtils {

	/**
	 * 用流的方式读取request中的body
	 */
	public static String getReqBody(HttpServletRequest request){
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
			List readLines = IOUtils.readLines(reader);
			StringBuilder sb = new StringBuilder();
			for (Object object : readLines) {
				sb.append(object.toString());
			}
			
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	/**
	 * 获取用户真实ip
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");   
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	        ip = request.getHeader("Proxy-Client-IP");   
	    }   
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	        ip = request.getHeader("WL-Proxy-Client-IP");   
	    }   
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	        ip = request.getRemoteAddr();   
	    }
	    return ip;
	}
	/**
	 * 获取sessionid
	 * @param request
	 * @return
	 */
	public static String getSessionId(HttpServletRequest request){
		return request.getSession().getId();
	}
}
